<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="页面标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="页面类型" prop="path">
        <el-input v-model="form.type" disabled></el-input>
      </el-form-item>
      <el-form-item label="页面路径" prop="path">
        <el-input v-model="form.path" disabled></el-input>
      </el-form-item>
      <el-form-item label="页面简介" prop="des">
        <el-input v-model="form.des"></el-input>
      </el-form-item>
      <!--      <el-form-item label="是否文章" prop="isArticle">-->
      <!--        <el-radio-group v-model="form.isArticle">-->
      <!--          <el-radio :value="1">是</el-radio>-->
      <!--          <el-radio :value="0">否</el-radio>-->
      <!--        </el-radio-group>-->
      <!--      </el-form-item>-->
      <el-form-item label="发布日期" prop="date">
        <el-date-picker
            type="datetime"
            v-model="form.publishTime"
            format="YYYY/MM/DD"
            value-format="x"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="顶部文章" prop="mainImg">
        <!-- <el-input style="width:500px" v-model="pageContent.ref_model"></el-input> -->
        <el-table :data="pageContent.main_info" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button
                  type="warning"
                  @click="
                  visibleMainInfoSelector = true;
                  visible =true;
                  selectorIndex = -1;
                "
              >添加
              </el-button
              >
            </template>

            <template #default="scope">
              <el-button size="small" @click="tableContentPreView(scope.row, 'maininfo')">预览</el-button>
              <el-button size="small" type="info"
                         @click="visibleMainInfoSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row,'maininfo')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="News Overview" prop="article">
        <el-table :data="pageContent.news_overview" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button type="warning" @click="visibleNewsSelector = true;visible=true;  selectorIndex = -1">添加
              </el-button>
            </template>
            <template #default="scope">
              <el-button size="small" @click="tableContentPreView(scope.row, 'article')">预览</el-button>
              <el-button size="small" type="info"
                         @click="visibleNewsSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row, 'newsoverview')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="Media Infos" prop="image">
        <el-table :data="pageContent.media_infos" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button
                  type="warning"
                  @click="
                  visibleMediaInfoSelector = true;
                  visible=true;
                  selectorIndex = -1;
                "
              >添加
              </el-button
              >
            </template>
            <template #default="scope">
              <el-button size="small" @click="tableContentPreView(scope.row, 'article')">预览</el-button>
              <el-button size="small" type="info"
                         @click="visibleMediaInfoSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row, 'mediainfo')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="Models" prop="art">
        <el-table :data="pageContent.models" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button
                  type="warning"
                  @click="
                  visibleModelSelector = true;
                  visible=true;
                  selectorIndex = -1;
                "
              >添加
              </el-button
              >
            </template>
            <template #default="scope">
              <el-button size="small" @click="tableContentPreView(scope.row, scope.row.path)">预览</el-button>
              <el-button size="small" type="info"
                         @click="visibleModelSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row, 'model')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="Pictures" prop="image">
        <el-table :data="pageContent.pictures" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button
                  type="warning"
                  @click="
                  visiblePicturesSelector = true;
                  visible=true;
                  selectorIndex = -1;
                "
              >添加
              </el-button
              >
            </template>
            <template #default="scope">
              <el-button size="small" type="info"
                         @click="visiblePicturesSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row, 'pictures')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="Videos" prop="image">
        <el-table :data="pageContent.videos" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button
                  type="warning"
                  @click="
                  visibleVideosSelector = true;
                  visible=true;
                  selectorIndex = -1;
                "
              >添加
              </el-button
              >
            </template>
            <template #default="scope">
              <el-button size="small" type="info"
                         @click="visibleVideosSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row, 'videos')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="Milestone" prop="image">
        <el-table :data="pageContent.milestone" border style="width: 100%">
          <el-table-column align="center" label="标题" prop="title"/>
          <el-table-column align="right">
            <template #header>
              <el-button
                  type="warning"
                  @click="
                  visibleMilestoneSelector = true;
                  visible=true;
                  selectorIndex = -1;
                "
              >添加
              </el-button
              >
            </template>
            <template #default="scope">
              <el-button size="small" type="info"
                         @click="visibleMilestoneSelector = true;visible=true; selectorIndex = scope.$index">更改
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row, 'milestone')"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="preView()">预览</el-button>
        <el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
        <el-button type="primary" v-if="form.isPublish == 0" @click="publish()"
        >发布
        </el-button
        >
        <el-button type="warning" v-if="form.isPublish == 2" @click="publish()"
        >更新
        </el-button
        >
        <el-button type="primary" @click="router.go(-1)">返 回</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
        v-model="visible"
        width="1300px"
        destroy-on-close
        :close-on-click-modal="false"
        @close="closeDialog"
    >
      <MaininfoSelector :updateTable="'maininfo'" v-if="visibleMainInfoSelector" :update="update"></MaininfoSelector>
      <ArticleSelector :updateTable="'newsoverview'" v-if="visibleNewsSelector" :update="update"></ArticleSelector>
      <ArticleSelector :updateTable="'mediainfo'" v-if="visibleMediaInfoSelector" :update="update"></ArticleSelector>
      <ModelSelector :updateTable="'model'" v-if="visibleModelSelector" :update="update"></ModelSelector>
      <ImageSelector :updateTable="'pictures'" v-if="visiblePicturesSelector" :update="update"></ImageSelector>
      <VideoSelector :updateTable="'videos'" v-if="visibleVideosSelector" :update="update"></VideoSelector>
      <MilestoneSelector :updateTable="'milestone'" v-if="visibleMilestoneSelector" :update="update"></MilestoneSelector>

      <!--    <ArticleSelector :updateTable="'model'" v-if="visibleMediaInfoSelector" :update="update"></ArticleSelector>-->

    </el-dialog>

  </div>


</template>

<script setup lang="ts">
import {
  ElMessage,
  ElMessageBox,
  FormInstance,
  FormRules,
  UploadProps,
} from "element-plus";
import {onBeforeUnmount, ref, reactive, shallowRef, onMounted} from "vue";
import {useRoute, useRouter} from "vue-router";
import ArticleSelector from "../../components/article-selector.vue";
import MilestoneSelector from "../../components/milestone-selector.vue";
import MaininfoSelector from "../../components/maininfo-selector.vue";
import PDFSelector from "../../components/pdf-selector.vue";
import imageSelector from "../../components/image-selector.vue";
import videoSelector from "../../components/video-selector.vue";
import ModelInfoEditor from "../../components/model-info-table-edit.vue";

import Editor from "../../components/editor.vue";
// 引入vue-json-editor模块
import base from "../../utils/base";
import page from "../../api/page";
import maininfo from "../../api/maininfo";
import ModelSelector from "../../components/model-selector.vue";
import Milestone from "../../api/milestone";

//首先在setup中定义
const route = useRoute();
const router = useRouter();

// 推荐新闻列表

// 编辑可视化
const visible = ref(false);
const visibleMainInfoSelector = ref(false);
const visibleNewsSelector = ref(false);
const visibleMediaInfoSelector = ref(false);
const visibleModelSelector = ref(false);
const visiblePicturesSelector = ref(false);
const visibleVideosSelector = ref(false);
const visibleMilestoneSelector = ref(false);

const selectorIndex = ref(-1);
// const mainInfoSelectorIndex = ref(-1);
// const newsSelectorIndex = ref(-1);
// const mediaInfoSelectorIndex = ref(-1);
// const modelSelectorIndex = ref(-1);
// const picturesSelectorIndex = ref(-1);
// const videosSelectorIndex = ref(-1);
// const milestoneSelectorIndex = ref(-1);

//

// const url = `${base.rq}/file/upload`;
const url = `${base.rq}/file/upload?token=${localStorage.getItem("token")}`


const defaultData = {
  id: "",
  title: "",
  modName: "",
  path: "",
  des: "",
  isArticle: 1,
  thumbnailUrl: "",
  pageContent: {},
  isPublish: 0,
  publishTime: "",
  articleType:"",

};

const form = ref({defaultData});
const thumb = ref();
console.log(thumb)
const pageContent = ref({
  main_info: [],
  news_overview: [],
  media_infos: [],
  models: [],
  pictures: [],
  videos: [],
  milestone: []
});


// 获取草稿内容
const getData = () => {
  page.getSketchById({id: route.query.id}, (res) => {
    if (res.code === 200) {
      form.value = res.data;
      form.value.publishTime = Number(form.value.publishTime);
      thumb.value = res.data.thumbnailUrl;

      if (res.data.pageContent) {
        pageContent.value = res.data.pageContent;
        // insertContent(form.value.pageContent);
        // console.log(pageContent.value)
      }
    }
  });
};
getData();

const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
  commit();
  console.log(form.value);
};

// json 保存
const commit = () => {
  // console.log(valueHtml)
  // pageContent.value["publishTime"] =
  form.value.pageContent = pageContent.value;
  if (form.value.isPublish === 1) {
    form.value.isPublish = 2;
  }
  page.save(form.value, (res) => {
    if (res.code === 200) {
      console.log(res);
      ElMessage.success("保存成功！");
      getData()
    } else {
      ElMessage.success("保存失败！");
    }
  });
};

// json 发布
const publish = () => {
  form.value.pageContent = pageContent.value;
  page.publish(form.value, (res) => {
    if (res.code === 200) {
      console.log(res);
      ElMessage.success("发布成功！");
      getData();
    } else {
      ElMessage.success("发布失败！");
      getData();
    }
  });
};

// json 下架
const unpublish = () => {
  form.value.pageContent = pageContent.value;
  page.unpublish(form.value, (res) => {
    if (res.code === 200) {
      console.log(res);
      ElMessage.success("下架成功！");
      getData();
    } else {
      ElMessage.success("下架失败！");
      getData();
    }
  });
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  // form.value.thumb = URL.createObjectURL(uploadFile.raw!);
  form.value.thumbnailUrl = response.data.realName;
  thumb.value = response.data.tmpUrl;
};

const closeDialog = () => {

  visible.value = false;
  visibleMainInfoSelector.value = false;
  visibleNewsSelector.value = false;
  visibleMediaInfoSelector.value = false;
  visibleModelSelector.value = false;
  visiblePicturesSelector.value = false;
  visibleVideosSelector.value = false;
  visibleMilestoneSelector.value = false;
};
const update = (content, tableName: string) => {
  if (tableName == "maininfo") {
    content["contentType"] = content.articleType;
    delete content.pageContent;
    // pageContent.value.main_info.push(content)
    if (selectorIndex.value == -1) {
      pageContent.value.main_info.push(content)
    } else {
      pageContent.value.main_info[selectorIndex.value] = content;
    }
  }
  if (tableName == "newsoverview") {
    content["contentType"] = content.articleType;
    delete content.pageContent;
    if (selectorIndex.value == -1) {
      pageContent.value.news_overview.push(content)
    } else {
      pageContent.value.news_overview[selectorIndex.value] = content;
    }
  }
  if (tableName == "mediainfo") {
    console.log(content)
    content["contentType"] = content.articleType;
    // content["doc"] = content.pageContent.doc;
    // console.log(content);
    delete content.pageContent;
    // pageContent.value.media_infos.push(content)
    if (selectorIndex.value == -1) {
      pageContent.value.media_infos.push(content)
    } else {
      pageContent.value.media_infos[selectorIndex.value] = content;
    }
  }
  if (tableName == "model") {
    delete content.pageContent;
    // pageContent.value.models.push(content)
    if (selectorIndex.value == -1) {
      pageContent.value.models.push(content)
    } else {
      pageContent.value.models[selectorIndex.value] = content;
    }
  }
  if (tableName == "pictures") {
    // console.log(content)
    // pageContent.value.pictures.push(content)
    if (selectorIndex.value == -1) {
      pageContent.value.pictures.push(content)
    } else {
      pageContent.value.pictures[selectorIndex.value] = content;
    }
  }
  if (tableName == "videos") {
    // pageContent.value.videos.push(content)
    if (selectorIndex.value == -1) {
      pageContent.value.videos.push(content)
    } else {
      pageContent.value.videos[selectorIndex.value] = content;
    }
  }
  if (tableName == "milestone") {
    content["contentType"] = content.articleType;
    delete content.pageContent;
    // pageContent.value.milestone.push(content)
    if (selectorIndex.value == -1) {
      pageContent.value.milestone.push(content)
    } else {
      pageContent.value.milestone[selectorIndex.value] = content;
    }
  }

  closeDialog();
};
//删除
const handleDelete = (index: number, row, tableName: string) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
      .then(() => {
        ElMessage.success("删除成功");
        if (tableName == "maininfo") {
          pageContent.value.main_info.splice(index, 1)
        }
        if (tableName == "newsoverview") {
          pageContent.value.news_overview.splice(index, 1)
        }
        if (tableName == "mediainfo") {
          pageContent.value.media_infos.splice(index, 1)
        }
        if (tableName == "model") {
          pageContent.value.models.splice(index, 1)
        }
        if (tableName == "pictures") {
          pageContent.value.pictures.splice(index, 1)
        }
        if (tableName == "videos") {
          pageContent.value.videos.splice(index, 1)
        }
        if (tableName == "milestone") {
          pageContent.value.milestone.splice(index, 1)
        }
      })
      .catch(() => {
      });
};


const tableContentPreView = (item, path) => {
  console.log(item)
  window.open(`${base.newsroom}/${path}/${item.id}?token=${localStorage.getItem("token")}`, "_blank");
};

const preView = () => {
  window.open(`${base.newsroom}?token=${localStorage.getItem("token")}`, "_blank");
};
</script>
<style>
.container {
  max-width: 1600px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.editor-container {
  width: 1000px;
}

.editor {
  padding: 0px;
}

.editor :deep(.jsoneditor-poweredBy) {
  display: none;
}

.avatar {
  width: 300px;
}
</style>
